package com.v1.video.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.v1.video.R;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.PayOrderConfig;
import com.v1.video.domain.PayOrderEntity;
import com.v1.video.engine.NetEngine;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.interfaces.OnPayListener;
import com.v1.video.pay.AlipayUtils;
import com.v1.video.pay.Key;
import com.v1.video.pay.PayResult;
import com.v1.video.pay.WeixinUtils;
import com.v1.video.util.Logger;
import com.v1.video.util.Utils;

/**
 * 支付订单页
 * 
 * @author wangfang
 * 
 */
public class PayActivity extends BaseActivity implements OnClickListener {

	private static final int RESULT_PAY = 100;
	private static final String PAY_ALI = "1"; // 支付宝支付
	private static final String PAY_WX = "12"; // 微信支付
	private IWXAPI mApi;
	private TextView mTvTitle, mTvName, mTvMoney;
	private CheckBox mCbxAlipay, mCbxWxpay;
	private String mName, mMoney, mVideoId, mDetail;
	private ProgressDialog pd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pay);
	}

	/**
	 * 初始化界面
	 */
	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		mTvTitle = (TextView) this.findViewById(R.id.tv_title);
		mTvName = (TextView) this.findViewById(R.id.tv_name);
		mTvMoney = (TextView) this.findViewById(R.id.tv_money);
		mCbxAlipay = (CheckBox) this.findViewById(R.id.rbn_alipay);
		mCbxWxpay = (CheckBox) this.findViewById(R.id.rbn_wxpay);
		mCbxAlipay.setTag(1);
		mCbxWxpay.setTag(2);
		mCbxAlipay.setChecked(true);
	}

	/**
	 * 初始化数据
	 */
	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		Intent intent = getIntent();
		mName = intent.getStringExtra("name");
		mMoney = intent.getStringExtra("money");
		mVideoId = intent.getStringExtra("videoId");
		mDetail = intent.getStringExtra("detail");
		mApi = WXAPIFactory.createWXAPI(this, Key.WX_APP_ID);
		mTvTitle.setText("打赏订单");
		if (!TextUtils.isEmpty(mName)) {
			mTvName.setText("视频名称：" + mName);
		} else {
			mTvName.setText("视频名称：");
		}
		if (!TextUtils.isEmpty(mMoney)) {
			mTvMoney.setText(mMoney + "元");
		} else {
			mTvMoney.setText("0元");
		}
	}

	/**
	 * 设置事件
	 */
	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		this.findViewById(R.id.lay_result).setOnClickListener(this);
		this.findViewById(R.id.lay_alipay).setOnClickListener(this);
		this.findViewById(R.id.lay_wxpay).setOnClickListener(this);
		this.findViewById(R.id.btn_ok).setOnClickListener(this);
		mCbxAlipay.setOnCheckedChangeListener(mOnCheckedChangeListener);
		mCbxWxpay.setOnCheckedChangeListener(mOnCheckedChangeListener);
	}

	/**
	 * 事件处理
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.lay_result:
			this.finish();
			break;
		case R.id.lay_alipay:
			mCbxAlipay.setChecked(true);
			break;
		case R.id.lay_wxpay:
			mCbxWxpay.setChecked(true);
			break;
		case R.id.btn_ok:
			if (LoginInfo.getInstance().isLogin()) {
				if (mCbxAlipay.isChecked() || mCbxWxpay.isChecked()) {
					String userId = LoginInfo.getInstance().getUserId();
					if (mCbxAlipay.isChecked()) {
						if (!TextUtils.isEmpty(mVideoId)
								&& !TextUtils.isEmpty(mMoney)) {
//							new PayOrderAsyncTask(userId, mVideoId, mMoney,
//									PAY_ALI).execute();
							getPayOrder(Key.PAY_ALI);
						}
					} else if (mCbxWxpay.isChecked()) {
						if (isInstalledWechat() && isSupportWechatPay()) {
							if (!TextUtils.isEmpty(mVideoId)
									&& !TextUtils.isEmpty(mMoney)) {
//								new PayOrderAsyncTask(userId, mVideoId, mMoney,
//										PAY_WX).execute();
								getPayOrder(Key.PAY_WX);
							}
						} else {
							showToast("请安装最新版微信!");
						}
					}
				} else {
					showToast("请选择支付方式");
				}
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 支付方式切换状态
	 */
	private OnCheckedChangeListener mOnCheckedChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			// TODO Auto-generated method stub
			mCbxAlipay.setChecked(true);
//			if (isChecked) {
//				int index = Integer.parseInt(buttonView.getTag().toString());
//				switch (index) {
//				case 1:
//					mCbxWxpay.setChecked(false);
//					break;
//				case 2:
//					mCbxAlipay.setChecked(false);
//					break;
//				default:
//					break;
//				}
//			} else {
//				int index = Integer.parseInt(buttonView.getTag().toString());
//				switch (index) {
//				case 1:
//					mCbxWxpay.setChecked(true);
//					break;
//				case 2:
//					mCbxAlipay.setChecked(true);
//					break;
//				default:
//					break;
//				}
//			}
		}
	};

	/**
	 * 判断微信释放安装
	 * 
	 * @return
	 */
	private boolean isInstalledWechat() {
		return (mApi.isWXAppInstalled() && mApi.isWXAppSupportAPI());
	}

	/**
	 * 判断微信释放支持支付
	 * 
	 * @return
	 */
	private boolean isSupportWechatPay() {
		return mApi.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
	}

	/**
	 * 打开打赏成功页
	 */
	private void openRewardSuccess() {
		Intent intent = new Intent();
		intent.setClass(this, RewardSuccessActivity.class);
		intent.putExtra("name", mName);
		intent.putExtra("money", mMoney);
		intent.putExtra("videoId", mVideoId);
		startActivity(intent);
		this.finish();
	}

	/**
	 * 支付宝支付
	 * 
	 * @param orderNo
	 * @param notifyurl
	 */
	private void getAlipay(final String orderNo, final String notifyurl) {
		// 必须异步调用
		Thread payThread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// 构造PayTask 对象
				String payInfo = AlipayUtils.getpayInfo(mName, mDetail, mMoney,
						orderNo, notifyurl);
				PayTask alipay = new PayTask(PayActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo);
				Message msg = new Message();
				msg.what = 0;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		});
		payThread.start();
	}

	/**
	 * 微信支付回调
	 */
	private OnPayListener mOnPayListener = new OnPayListener() {

		@Override
		public void onPayListener(int code) {
			// TODO Auto-generated method stub
			WeixinUtils.setmOnPayListener(null);
			switch (code) {
			case 0: // 支付成功
				openRewardSuccess();
				break;
			case -1: // 签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
				showToast("打赏失败");
				break;
			case -2: // 用户取消
				showToast("取消打赏");
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 支付宝数据解析
	 */
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0: {
				PayResult payResult = new PayResult((String) msg.obj);
				// 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
				String resultInfo = payResult.getResult();
				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					openRewardSuccess();
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						showToast("打赏结果确认中");
					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						showToast("打赏失败");
					}
				}
				break;
			}
			default:
				break;
			}
		};
	};
	
	/**
	 * 获取支付订单
	 */
	private void getPayOrder(final String payWay) {
		pd = Utils.getProgressDialog(PayActivity.this, "正在支付订单...");
		pd.show();
		new NetEngine().getPayOrder(this, LoginInfo.getInstance().getUserId(),
				mVideoId, payWay, new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String keyId) {
						// TODO Auto-generated method stub
						dismiss();
						if (object != null) {
							PayOrderEntity entity = (PayOrderEntity) object;
							if (entity != null && entity.getBody() != null
									&& entity.getBody().getData() != null) {

								PayOrderEntity.PayOrder payOrder = entity
										.getBody().getData();
								if (TextUtils.isEmpty(payOrder.getResult())) {
									if (Key.PAY_ALI.equals(payWay)) {
										// getAlipay(payOrder.getPayno(),
										// payOrder.getCallbackurl());
										transferPay(payOrder.getPayno(),
												payOrder.getUrl());
									} else if (Key.PAY_WX.equals(payWay)) {
										if (mApi != null) {
											PayReq req = WeixinUtils.getPayReq(payOrder);
											WeixinUtils.setmOnPayListener(mOnPayListener);
											mApi.registerApp(Key.WX_APP_ID);
											mApi.sendReq(req);
										}
									}
								} else {
									showToast(payOrder.getResult());
								}
							}
						}
					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						dismiss();
						Logger.i(TAG, message);
					}

				});
	}

	private void dismiss() {
		if (pd != null) {
			if (pd.isShowing()) {
				pd.dismiss();
			}
			pd = null;
		}
	}
	
	private void transferPay(String orderNo, String url) {
		String orderInfo = AlipayUtils.getWebOrderInfo(mName, mDetail, mMoney,
				orderNo);
		Intent intent = new Intent();
		intent.setClass(this, WebViewActivity2.class);
		intent.putExtra("title", "支付订单");
		intent.putExtra("adLink", url);
		intent.putExtra("data", orderInfo);
		intent.putExtra("flag", WebViewActivity2.PAY_FLAG_LIVE);
		startActivityForResult(intent, RESULT_PAY);
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		switch (arg0) {
		case RESULT_PAY:
			if (arg1 == RESULT_OK && arg2 != null) {
				String flag = arg2.getStringExtra("flag");
				if (!TextUtils.isEmpty(flag) && flag.equals("1")) {
					openRewardSuccess();
				}
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 获取支付订单
	 * 
	 * @author wangf
	 * 
	 */
	private class PayOrderAsyncTask extends
			AsyncTask<Void, Void, PayOrderConfig> {

		private String errorMsg;
		private String userId;
		private String videoId;
		private String money;
		private String payWay;

		public PayOrderAsyncTask(String userId, String videoId, String money,
				String payWay) {
			this.userId = userId;
			this.videoId = videoId;
			this.money = money;
			this.payWay = payWay;
		}

		@Override
		protected void onPreExecute() {
			pd = Utils.getProgressDialog(PayActivity.this, "正在支付订单...", this);
			pd.show();
		}

		@Override
		protected PayOrderConfig doInBackground(Void... params) {

			try {
				return new NetEngine().getPayOrder(userId, videoId, money,
						payWay);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				errorMsg = e.getMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(PayOrderConfig result) {
			if (pd != null) {
				pd.dismiss();
			}
			pd = null;
			if (result != null && result.getObj() != null) {
				if (PAY_ALI.equals(payWay)) {
					getAlipay(result.getObj().getPayno(), result.getObj()
							.getCallbackurl());
				} else if (PAY_WX.equals(payWay)) {
					if (mApi != null) {
//						PayReq payreq = WeixinUtils.getPayReq(result.getObj());
//						WeixinUtils.setmOnPayListener(mOnPayListener);
//						mApi.registerApp(Key.WX_APP_ID);
//						mApi.sendReq(payreq);
					}
				}
			} else {
				if (!TextUtils.isEmpty(errorMsg)) {
					Toast.makeText(PayActivity.this, errorMsg,
							Toast.LENGTH_SHORT).show();
				}
			}
		}
	}
}
